﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Common.Architecture.Common
{
    public class JwtTools
    {
        public string JwrNewString(IConfiguration configuration,string uid)
        {
            //2.生产JWT
            //Header，选择签名算法
            var singingAlogorithm=SecurityAlgorithms.HmacSha256;
            //payload，存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Name,"张三"),
                new Claim(ClaimTypes.Email,"zhangsan@example.com"),
                new Claim(ClaimTypes.Role,"Admin"),
                new Claim(ClaimTypes.DateOfBirth,"1980-01-01",ClaimValueTypes.Date),
                new Claim("CustomClaimType","CustomValue"),
                new Claim("key","value值")
            };
            //signature
            //取出私钥并以UTF8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey=new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的密钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, singingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],//发布
                audience:configuration["Authentication:Audience"],//接收
                claims:claims,notBefore:DateTime.UtcNow,//存放时间
                expires:DateTime.UtcNow.AddDays(1),//有效期设置为1天
                signingCredentials//数字签名
                                  );

            var TokenStr=new JwtSecurityTokenHandler().WriteToken(Token);

            return TokenStr;
        }
    }
}
